<?php
/**
 * Creates and manages interaction for the upload form shortcode.
 */
class DocCentre_Upload_Shortcode
{
	/**
	 * Reference to the DocCentre system object.
	 * 
	 * @var DocCentre
	 */
	protected $system;
	
	/**
	 * Contains any feedback from the file upload process.
	 * 
	 * @var string
	 */
	protected $feedback = '';
	
	
	
	/**
	 * Creates and manages interaction for the upload form shortcode.
	 * 
	 * @param DocCentre $system
	 * @return DocCentre_Upload_Shortcode
	 */
	public function __construct(DocCentre $system)
	{
		$this->system = $system;
		
		add_action('init', array($this, 'handle_uploads'));
		add_shortcode('doccentre_upload_form', array($this, 'controller'));
	}
	
	
	/**
	 * Detects and handles uploads.
	 */
	public function handle_uploads()
	{
		if ($this->upload_form_submitted() and $this->security_check())
		{
			if ($this->system->library->add_document('document'))
				$this->feedback = 'success';
			else
				$this->feedback = 'failure';
		}
	}
	
	
	/**
	 * Handles shortcodes requests.
	 * 
	 * @param mixed $attributes
	 * @param mixed $content = null
	 */
	public function controller($attributes, $content = null)
	{		
		return $this->display_form(array('result' => $this->feedback));
	}
	
	
	/**
	 * Checks if the upload form has been submitted.
	 * 
	 * @return bool
	 */
	protected function upload_form_submitted()
	{
		if (!isset($_POST)) return false;
		if (!array_key_exists('document', $_FILES)) return false;
		if (!array_key_exists('senddoc', $_POST)) return false;
		
		return true;
	}
	
	
	/**
	 * Checks that nonce was valid for this submission.
	 * 
	 * @return bool
	 */
	protected function security_check()
	{
		if (!current_user_can('upload_files')) return false;
		if (!array_key_exists('_wpnonce', $_POST)) return false;
		if (!wp_verify_nonce($_POST['_wpnonce'], 'doccentre-upload')) return false;
		
		return true;
	}
	
	
	/**
	 * Renders the upload form, passing any variables contained within
	 * array $vars.
	 * 
	 * @param array $vars
	 */
	protected function display_form(array $vars = null)
	{
		$defaults = array(
			'form_action' => $this->system->request_url()
		);
		
		$vars = array_merge($defaults, (array) $vars);
		
		// Display the upload form only if the user has appropriate capability
		if (current_user_can('upload_files'))
			return $this->system->load_template('upload', $vars);
			
		else return $this->system->load_template('no_upload');
	}
}